//
//  loginViewController.m
//  AdvertisementI
//
//  Created by mac on 16/5/19.
//  Copyright © 2016年 Apple inc. All rights reserved.
//

#import "loginViewController.h"
#import "ViewController.h"
@interface loginViewController ()

@end

@implementation loginViewController

-(void)viewWillAppear:(BOOL)animated
{
    //http://blog.it985.com/13140.html
    self.tabBarController.tabBar.hidden = YES;//影藏tabBar

    [self.navigationItem.backBarButtonItem setTitle:@""];
    [self.navigationItem setHidesBackButton:YES];//以上两句如同上三句
    
}
 //触摸开始  当手指触摸屏幕时，取消第一响应（回收键盘）
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor = BuleColor;
    self.view.backgroundColor = [UIColor whiteColor];
    _loginCountryView = [[VPNLabelAndTextFieldView alloc]initWithFrame:CGRectMake(15, 64, kScreenW-30, kScreenH*0.08)];
    _loginCountryView.nameLabel.text = @"国家/地区";
    _loginCountryView.valueField.placeholder = @"请输入国家或地区";
    
    _loginPhoneNumberView = [[VPNLabelAndTextFieldView alloc]initWithFrame:CGRectMake( 15,64+kScreenH*0.08,kScreenW-30, kScreenH*0.08)];
    _loginPhoneNumberView.nameLabel.text = @"用户名";
    _loginPhoneNumberView.valueField.placeholder = @"输入账号";
    _loginPhoneNumberView.valueField.keyboardType = UIKeyboardTypeDefault;
    
    _loginPasswordView= [[VPNLabelAndTextFieldView alloc]initWithFrame:CGRectMake( 15, 64+kScreenH*0.16,kScreenW-30, kScreenH*0.08)];
    _loginPasswordView.nameLabel.text = @"密码";
    _loginPasswordView.valueField.placeholder = @"输入密码";
    _loginPasswordView.valueField.secureTextEntry = YES; //使输入框成为密码框
    
    [self.view addSubview:_loginCountryView];
    [self.view addSubview:_loginPhoneNumberView];
    [self.view addSubview:_loginPasswordView];
    
//    登陆按钮
    _loginButton = [[UIButton alloc]initWithFrame:CGRectMake(15, 64+kScreenH*0.24+20, kScreenW-30, kScreenH*0.08)];
    _loginButton.backgroundColor = BuleColor;
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.view addSubview:_loginButton];
    _loginButton.layer.borderWidth =1; //设置框线条的宽度
    _loginButton.layer.borderColor = [UIColor whiteColor].CGColor;//设置框线条的颜色
    [_loginButton.layer setCornerRadius:8];//使框的四个角为圆弧型
    [_loginButton addTarget:self action:@selector(hitLoginBt:) forControlEvents:UIControlEventTouchUpInside];
//    注册按钮
    _loginRegisterButton = [[UIButton alloc]initWithFrame:CGRectMake(kScreenW-60-30, 64+kScreenH*0.32+20, 60, kScreenH*0.05)];
    [_loginRegisterButton setTitle:@"注册" forState:UIControlStateNormal];
    [_loginRegisterButton setTitleColor:[UIColor colorWithRed:100/255.0 green:199/255.0 blue:250/255.0 alpha:1] forState:UIControlStateNormal];
    [self.view addSubview:_loginRegisterButton];
    [_loginRegisterButton addTarget:self action:@selector(hitLoninRegisterBt:) forControlEvents:UIControlEventTouchUpInside];
//    忘记密码
    _forgetPasswordButton = [[UIButton alloc]initWithFrame:CGRectMake(30, 64+kScreenH*0.32+20, 80, kScreenH*0.05)];
    [_forgetPasswordButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [_forgetPasswordButton setTitleColor:[UIColor colorWithRed:100/255.0 green:199/255.0 blue:250/255.0 alpha:1] forState:UIControlStateNormal];
    [self.view addSubview:_forgetPasswordButton];

}
#pragma mark ---按钮回调事件----
//点击登录界面的注册按钮
- (void)hitLoninRegisterBt:(UIButton *)sender{
    [self.view endEditing:YES];
        registerViewController * vc =[[registerViewController alloc ]init];
    [self.navigationController pushViewController:vc animated:NO];
}
//登陆按钮
- (void)hitLoginBt:(UIButton *)sender{
   
    [self.view endEditing:YES];
    //判断名字是否为2到10个字节的中文或者汉字
    if ([self validateNickname:_loginPhoneNumberView.valueField.text]) {
        //判断密码是否为6到12位的字母或者数字
        if ([self isPassword:_loginPasswordView.valueField.text]) {
        //调用登陆接口
            [self loginhttp];

        }else{
            AlertController(@"密码为6到12位的字母或者数字");
        }
    }else{
        AlertController(@"名字为2到10个中文,字母或者数字");
    }
    
}
//登陆接口
-(void)loginhttp
{
//    初始化网络请求工具类
    AFHTTPRequestOperationManager *manager =[[AFHTTPRequestOperationManager alloc]init];
    manager.responseSerializer =[AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"loginname":_loginPhoneNumberView.valueField.text, @"loginpwd":_loginPasswordView.valueField.text};//47.88.76.185  47.88.19.232
    [manager POST:@"http://47.88.76.185:8080/Test/app_login" parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary*dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
         //         NSString *rcode = [dic objectForKey:@"rcode"];
         int rcode = [[dic objectForKey:@"rcode"] intValue];
         NSLog(@"===%@",dic);
         if (!rcode){
              AlertController(@"用户名或密码错误");
         }
         else{
             _userdefults1 = [NSUserDefaults standardUserDefaults];
             [_userdefults1 setValue:_loginPhoneNumberView.valueField.text forKey:@"logname"];
             AlertController(@"登录成功");
             //代码能走到这里说明已经登录成功
             NSDictionary * dicToken = [dic objectForKey:@"pageData"];
             NSString *token = [dicToken objectForKey:@"password"];//NSString *token
             float time = [[dic objectForKey:@"time"] floatValue];
             NSDate *now = [NSDate date];
             NSDate *endTime = [now dateByAddingTimeInterval:time];
             [APP_DEF setObject:token forKey:TOKEN_KEY];
             [APP_DEF setObject:endTime forKey:TIME_KEY];
             [APP_DEF setObject:_loginPhoneNumberView.valueField.text forKey:USER_NAME];//存储当前登录的用户名
             [APP_DEF synchronize];
//             if (self.complete) {   
//                 self.complete(YES);
                 __block ViewController *viewController = [[ViewController alloc]init];
                 [viewController goToMainVC];
//             }
         }
     } failure:nil];
}
//手机号码的正则表达式
- (BOOL) isMobile:(NSString *)mobileNumbel{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}

//判断密码是否为6到12位的字母或者数字
- (BOOL)isPassword:(NSString *)password
{
    NSString *      regex = @"(^[A-Za-z0-9]{6,20}$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:password];
}

//判断名字是否为2到10个字节的中文或者汉字
- (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"[\u4e00-\u9fa5_a-zA-Z0-9_]{2,10}";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
